<template>
  <a-modal v-model:open="open" width="100%"
           wrap-class-name="full-modal"
           :footer="null"
           :keyboard="false"
           :mask-closable="false"
           title="添加商品"
           @cancel="handleClose">
    <a-form
        :model="formState"
        name="basic"
        class="mt20"
        layout="horizontal"
        style="width: 100%;"
        ref="formRef"
        :rules="rules"
        :label-col=" { style: { width: '150px' } }"
        :wrapper-col="{ span: 24}"
        autocomplete="off"
    >
      <a-row class="flex justify-between">
        <a-col :span="11">
          <a-form-item
              label="门店名称"
              name="shopsId"
          >
            <a-select
                v-model:value="formState.shopsId"
                class="w100"
                placeholder="请选择门店"
                @change="handleChange"
            >
              <a-select-option v-for="shop in shopList" :value="shop.id">{{ shop.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
              label="商品名称"
              name="name"
          >
            <a-input v-model:value="formState.name" placeholder="请输入商品名称"/>
          </a-form-item>

          <a-form-item label="商品描述"
                       name="detail"
          >
            <a-textarea :rows="4" v-model:value="formState.detail" placeholder="请输入商品描述！"/>
          </a-form-item>

          <a-form-item
              label="商品原价格"
              name="originalPrice"
          >
            <a-input-number placeholder="请输入商品价格" class="w100" v-model:value="formState.originalPrice"/>
          </a-form-item>

          <a-form-item
              label="商品一口价"
              name="price"
          >
            <a-input-number placeholder="请输入商品价格" class="w100" v-model:value="formState.price"/>
          </a-form-item>

          <a-form-item
              label="商品折扣价"
              name="salePrice"
          >
            <a-input-number placeholder="请输入商品折扣价" class="w100" v-model:value="formState.salePrice"/>
          </a-form-item>
          <a-form-item label="商品主图" name="mainImage">
            <a-upload :action="getBaseURL()+'/oss/upload/file'"
                      :headers="headers"
                      :multiple="false"
                      :data="{'path':'goods'}"
                      v-model:file-list="fileList1"
                      @change="handleUploadSuccess"
                      list-type="picture-card">
              <div>
                <PlusOutlined/>
                <div style="margin-top: 8px">选择图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="商品子图" name="subImages">
            <a-upload :action="getBaseURL()+'/oss/upload/file'"
                      :headers="headers"
                      :data="{'path':'goods'}"
                      v-model:file-list="fileList2"
                      @change="handleUploadSuccess1"
                      list-type="picture-card">
              <div>
                <PlusOutlined/>
                <div style="margin-top: 8px">选择图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="详情图片" name="detailImages">
            <a-upload :action="getBaseURL()+'/oss/upload/file'"
                      :headers="headers"
                      :data="{'path':'goods'}"
                      v-model:file-list="fileList3"
                      @change="handleUploadSuccess2"
                      list-type="picture-card">
              <div>
                <PlusOutlined/>
                <div style="margin-top: 8px">选择图片</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="购买须知"
                       name="buyTips"
          >
            <a-textarea :rows="4" v-model:value="formState.buyTips" placeholder="请输入购买须知！"/>
          </a-form-item>

          <a-form-item
              label="库存"
              name="stock"
          >
            <a-input-number placeholder="请输入商品库存" class="w100" v-model:value="formState.stock"/>
          </a-form-item>
          <a-form-item
              label="月销量"
              name="monthlySales"
          >
            <a-input-number placeholder="请输入月销量" class="w100" v-model:value="formState.monthlySales"/>
          </a-form-item>

          <a-form-item
              label="累计销量"
              name="totalSales"
          >
            <a-input-number placeholder="请输入累计销量" class="w100" v-model:value="formState.totalSales"/>
          </a-form-item>
          <a-form-item
              label="累计评价"
              name="totalComments"
          >
            <a-input-number placeholder="请输入累计评价" class="w100" v-model:value="formState.totalComments"/>
          </a-form-item>

          <a-form-item
              label="包装费"
              name="packingCharges"
          >
            <a-input-number placeholder="请输入包装费" class="w100" v-model:value="formState.packingCharges"/>
          </a-form-item>

          <a-form-item
              label="排序号"
              name="sortNumber"
          >
            <a-input-number placeholder="请输入排序号" class="w100" v-model:value="formState.sortNumber"/>
          </a-form-item>

          <a-form-item
              label="是否商家推荐菜"
              name="recommendedByMerchants"
          >
            <a-switch v-model:checked="formState.recommendedByMerchants"
                      :checked-value="1"
                      :un-checked-value="0"
                      checked-children="是"
                      un-checked-children="否"/>
          </a-form-item>
          <a-form-item
              label="是否用户推荐菜"
              name="recommendedByMember"
          >
            <a-switch v-model:checked="formState.recommendedByMember"
                      :checked-value="1"
                      :un-checked-value="0"
                      checked-children="是"
                      un-checked-children="否"/>
          </a-form-item>

          <a-form-item
              label="用户推荐菜人数"
              name="numberOfRecommendedMember"
          >
            <a-input-number placeholder="请输入用户推荐菜人数" class="w100"
                            v-model:value="formState.numberOfRecommendedMember"/>
          </a-form-item>

          <a-form-item
              label="优惠名称"
              name="preferentialName"
          >
            <a-input placeholder="请输入优惠名称" class="w100" v-model:value="formState.preferentialName"/>
          </a-form-item>

          <a-form-item
              label="是否热门"
              name="isHot"
          >
            <a-switch v-model:checked="formState.isHot"
                      :checked-value="1"
                      :un-checked-value="0"
                      checked-children="是"
                      un-checked-children="否"/>
          </a-form-item>


          <a-form-item
              label="是否最新"
              name="isNew"
          >
            <a-switch v-model:checked="formState.isNew"
                      :checked-value="1"
                      :un-checked-value="0"
                      checked-children="是"
                      un-checked-children="否"/>
          </a-form-item>

          <a-form-item
              label="是否开启促销"
              name="isSale"
          >
            <a-switch v-model:checked="formState.isSale"
                      :checked-value="1"
                      :un-checked-value="0"
                      checked-children="是"
                      un-checked-children="否"/>
          </a-form-item>

          <a-form-item>
            <a-button style="margin-left: 150px" type="primary" @click.stop.prevent="onSubmit">{{formState.id?'更新商品':'保存商品'}}</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script setup>
import dayjs from 'dayjs';
import {getSystemId, getSystemName, getBaseURL} from "@/config/common.js";
const token = useCookie("CC_TOKEN").value
const headers = {"systemId": getSystemId, "systemName": getSystemName, "token": token}
const dateFormat = 'YYYY-MM-DD HH:mm:ss';
const open = ref(false);
const formRef = ref({})
const fileList1 = ref([]);
const fileList2 = ref([]);
const fileList3 = ref([]);

const emits = defineEmits(["success"])
const formState = ref({
  shopsId: null,
  name: '',
  shopsName: '',
  mainImage: '',
  subImages: '',
  detailImages: '',
  detail: '',
  originalPrice: 0,
  price: 0,
  stock: 0,
  isHot: 0,
  isNew: 0,
  status: 1,
  isSale: 0,
  salePrice: 0,
  monthlySales: 0,
  totalSales: 0,
  totalComments: 0,
  preferentialName: '',
  packingCharges: 0,
  sortNumber: 1,
  recommendedByMerchants: 0,
  recommendedByMember: 0,
  numberOfRecommendedMember: 0,
  buyTips: ''
});

// 验证规则
const rules = {
  shopsId: [{required: true, message: '请选择店铺！', trigger: 'change'}],
  name: [
    {required: true, message: '请输入商品名称', trigger: 'change'},
    {min: 2, max: 30, message: '长度2到30位', trigger: 'blur'},
  ],
  price: [{required: true, message: '请输入商品价格！', trigger: 'blur'}],
  mainImage: [{required: true, message: '请选择图片！', trigger: 'blur'}],
};

const shopList = ref([])
const handleLoadShopList = async () => {
  const res = await useLoadShopLists()
  shopList.value = res.data;
}

const handleChange = (e) => {
  formState.value.shopsName = shopList.value.find(c => c.id == e).name;
}


const onSubmit = async () => {
  try {
    await formRef.value.validate()
    formState.value.mainImage = handleTransferURL(fileList1.value)
    formState.value.subImages = handleTransferURL(fileList2.value)
    formState.value.detailImages = handleTransferURL(fileList3.value)
    if (formState.value.id) {
      formState.value.id = formState.value.id * 1
      await useUpdateGoods(formState.value)
    } else {
      await useSaveGoods(formState.value)
    }
    useMessage().success("操作成功")
    handleClose()
    emits("success")
  } catch (e) {

  }
};


const handleUploadSuccess = (info) => {
  if (info.file.status === 'done') {
    info.fileList.map(c=>{
      if(c.response && c.response.data)c.url = c.response?.data?.url
    })
  }
}


const handleUploadSuccess1 = (info) => {
  if (info.file.status === 'done') {
    info.fileList.map(c=>{
      if(c.response && c.response.data)c.url = c.response?.data?.url
    })
  }
}

const handleUploadSuccess2 = (info) => {
  if (info.file.status === 'done') {
    info.fileList.map(c=>{
      if(c.response && c.response.data)c.url = c.response?.data?.url
    })
  }
}


const handleTransferURL = (imgs) => {
  if (typeof imgs === "string") return imgs
  if (imgs && imgs.length > 0) {
    let imgArr = imgs.map(c => c.url).join(',')
    return imgArr
  } else {
    return ''
  }
}

const handleTransferImage = (imgs) => {
  if (imgs && imgs.length > 0) {
    imgs = imgs.split(',')
    let imgArr = imgs.map(c => {
      return {
        uid: getUUID(),
        name: getUUID(),
        url: c,
        thumbUrl: c,
        status: "done",
      }
    })
    return imgArr
  } else {
    return []
  }
}

const handleOpen = async (opid) => {
  open.value = true
  await handleLoadShopList()
  if (opid) {
    formState.value.id = opid * 1;
    const res = await useGetGoodsById(opid)
    formState.value = {...res.data}
    fileList1.value = handleTransferImage(formState.value.mainImage)
    fileList2.value = handleTransferImage(formState.value.subImages)
    fileList3.value = handleTransferImage(formState.value.detailImages)
  }
}

const handleClose = () => {
  open.value = false
  fileList1.value = [];
  fileList2.value = [];
  fileList3.value = [];
  formState.value = {
    shopsId: null,
    name: '',
    shopsName: '',
    mainImage: [],
    subImages: [],
    detailImages: [],
    detail: '',
    originalPrice: 0,
    price: 0,
    stock: 0,
    isHot: 0,
    isNew: 0,
    status: 1,
    isSale: 0,
    salePrice: 0,
    monthlySales: 0,
    totalSales: 0,
    totalComments: 0,
    preferentialName: '',
    packingCharges: 0,
    sortNumber: 1,
    recommendedByMerchants: 0,
    recommendedByMember: 0,
    numberOfRecommendedMember: 0,
    buyTips: ''
  }
}

defineExpose({
  handleOpen
})
</script>

<style lang="scss">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }

  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
    overflow: auto;
    border-radius: 0px;
  }

  :where(.css-dev-only-do-not-override-1hsjdkk).ant-modal .ant-modal-header {
    background: transparent;
  }

  .ant-modal-body {
    flex: 1;
  }
}
</style>